/**
 *归并排序
 */
public class MergeSort {
    //1.递归实现
    public static void mergeSort(int[] array) {
        mergeSortFunction(array,0,array.length-1);
    }

    private static void mergeSortFunction(int[] array,int low,int high) {
        if(low >= high) {
            return;
        }
        int mid = (low+high) >>> 1;
        mergeSortFunction(array,low,mid);
        mergeSortFunction(array,mid+1,high);
        mergeGettogether(array,low,high,mid);
    }

    //2.非递归
    public static void mergeSort2(int[] array) {
        int gap = 1;
        while (gap < array.length) {
            for (int i = 0; i < array.length; i += gap*2 ) {
                int low = i;
                int mid = low+gap-1;
                if(mid >= array.length) {
                    mid = array.length-1;
                }
                int high = mid+gap;
                if(high >= array.length) {
                    high = array.length-1;
                }
                mergeGettogether(array,low,high,mid);
            }
            gap = gap*2;
        }
    }

    private static void mergeGettogether(int[] array,int low,int high,int mid) {
        int[] tmp = new int[high-low+1];
        int k = 0;
        int s1 = low;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = high;
        while (s1 <= e1 && s2 <= e2) {
            //两个归并段  都有数据
            if(array[s1] <= array[s2]) {
                tmp[k++] = array[s1++];
            }else {
                tmp[k++] = array[s2++];
            }
        }
        while (s1 <= e1) {
            tmp[k++] = array[s1++];
        }
        while (s2 <= e2) {
            tmp[k++] = array[s2++];
        }
        for (int i = 0; i < k; i++) {
            array[i+low] = tmp[i];
        }
    }

    public static void main(String[] args) {
        int[] array1={0,5,9,7,8,3,1,2,6,4};

        for (int x:
                array1) {
            System.out.println(x);
        }
    }

}
